//
//  UIViewController+MLXExample.m
//  MLX
//
//  Created by SY on 2018/10/22.
//  Copyright © 2018年 SY. All rights reserved.
//

#import "UIViewController+MLXExample.h"
#import <objc/runtime.h>
@implementation UIViewController (MLXExample)
#pragma mark - swizzle
+ (void)load
{
#ifdef DEBUG
    Method method1 = class_getInstanceMethod([self class], NSSelectorFromString(@"dealloc"));
    Method method2 = class_getInstanceMethod([self class], @selector(deallocSwizzle));
    method_exchangeImplementations(method1, method2);
    
    //原本的viewWillAppear方法
    Method viewWillAppear = class_getInstanceMethod(self, @selector(viewWillAppear:));
    
    //需要替换成 能够输出日志的viewWillAppear
    Method logViewWillAppear = class_getInstanceMethod(self, @selector(logViewWillAppear:));
    
    //两方法进行交换
    method_exchangeImplementations(viewWillAppear, logViewWillAppear);
#endif
}
- (void)deallocSwizzle{
    NSLog(@"%@被销毁了", self);
    [self deallocSwizzle];
}

static char MethodKey;
- (void)setMethod:(NSString *)method
{
    objc_setAssociatedObject(self, &MethodKey, method, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)method
{
    return objc_getAssociatedObject(self, &MethodKey);
}
- (void)logViewWillAppear:(BOOL)animated {
#ifdef DEBUG
    NSString *className = NSStringFromClass([self class]);
    //在这里，你可以进行过滤操作，指定哪些viewController需要打印，哪些不需要打印
    if ([className hasPrefix:@"UI"] == NO) {

        NSLog(@"%@ will appear",className);
    }
    //下面方法的调用，其实是调用viewWillAppear
#endif
    [self logViewWillAppear:animated];
}

@end
